if SERVER then
	AddCSLuaFile("shared.lua")

	util.AddNetworkString( "netinventory" )
	util.AddNetworkString( "netinventorySpawn" )
	util.AddNetworkString( "openmyinv" )
end

if CLIENT then
	SWEP.PrintName = "Inventory"
	SWEP.Slot = 1
	SWEP.SlotPos = 1
	SWEP.DrawAmmo = false
	SWEP.DrawCrosshair = true
end

SWEP.Base = "weapon_cs_base2"

SWEP.Author = "Carocrazy132 -- Derived from Pocket by FPtje"
SWEP.Instructions = "Left click to pick up, right click to drop, reload to open inventory"
SWEP.Contact = ""
SWEP.Purpose = ""
SWEP.IconLetter = ""

SWEP.ViewModelFOV = 62
SWEP.ViewModelFlip = false
SWEP.AnimPrefix	 = "rpg"

SWEP.Spawnable = false
SWEP.AdminSpawnable = true
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = 0
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = ""

SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = 0
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = ""

SWEP.InvOpen = 0


local DropItem

if CLIENT then
	SWEP.FrameVisible = false
	playerIsChatting=false
end



function SWEP:Initialize()
	self:SetWeaponHoldType("normal")
	
	if CLIENT then
		
		if (not self.Inventorymenu2) and !self.Inventorymenu2 and (not LocalPlayer():GetTable().madeInventory) then
			self.Inventorymenu2 = vgui.Create("DFrame")
	    	self.Inventorymenu2:SetSize(242,25)
	    	self.Inventorymenu2:SetPos(ScrW()-self.Inventorymenu2:GetWide()-65,ScrH()-38)
	    	self.Inventorymenu2:SetTitle("Inventory  ( Reload with SWEP )")
	    	self.Inventorymenu2:SetDraggable(false)
	    	self.Inventorymenu2:ShowCloseButton(false)
	    	LocalPlayer():GetTable().madeInventory = true
    	end

    	hook.Add( "KeyPress","inventoryopener",function(P, key)
    		if P==LocalPlayer() and key==IN_SCORE and self.InvOpen==0 then
    			self.InvOpen=1
    			net.Start("openmyinv")
				net.SendToServer()
    		end
    	end)

    	hook.Add( "KeyRelease","inventorycloser",function(P, key)
    		if P==LocalPlayer() and key==IN_SCORE and IsValid(Inventorymenu) and self.InvOpen==1 then
    			self.InvOpen=0
    			Inventorymenu:Close()
    		end
    	end)
    
    end

	if CLIENT then return end
end

function SWEP:Deploy()
	if SERVER then
		self.Owner:DrawViewModel(false)
		self.Owner:DrawWorldModel(false)
	end
end


local whitelist = {"spawned_shipment", "spawned_weapon", "gunlab", "normal_money_printer", "ruby_money_printer", "gold_money_printer", "nuclear_money_printer" }
-- simpleEnts are also whitelisted
local simpleEnts = {"weed_plant", "durgz_weed", "hash_ball", "personalhitphone", "durgz_mushroom", "durgz_lsd", "durgz_alcohol", "durgz_cocaine", "durgz_heroine", "durgz_aspirin",
"durgz_water","durgz_cigarette"}

function SWEP:PrimaryAttack()
	self.Weapon:SetNextPrimaryFire(CurTime() + 0.2)
	local trace = self.Owner:GetEyeTrace()
	local CurEnt = trace.Entity

	if not IsValid(CurEnt) or (SERVER and CurEnt:IsPlayerHolding()) then
		return
	end


	if self.Owner:EyePos():Distance(trace.HitPos) > 65 then
		return
	end


	self:SetWeaponHoldType("pistol")
	timer.Simple(0.2, function() if self:IsValid() then self:SetWeaponHoldType("normal") end end)
	if CLIENT then return end


	local phys = CurEnt:GetPhysicsObject()
	if not phys:IsValid() then 
		GAMEMODE:Notify(self.Owner, 1, 4, "not a valid ent")
		return 
	end


	inventoryItem(CurEnt,self.Owner)
end

function inventoryItem(CurEnt,ply)
	ply:GetTable().Inventory = ply:GetTable().Inventory or {}	

	if #ply:GetTable().Inventory >= GAMEMODE.Config.pocketitems then
		GAMEMODE:Notify(ply, 1, 4, "Your inventory is full!")
		return
	end


	local EntClass = CurEnt:GetClass()
	
	local Steam = ply:SteamID()

	local Item = {model="", amount=0, key=0, wasowned=0, labprice=0, storedmoney=0, weaponclass="", vehiclescript="", clip1=-1, clip2=-1}
	Item.model = CurEnt:GetModel()
	
	if table.HasValue(whitelist, EntClass) or table.HasValue(simpleEnts, EntClass) or CurEnt:IsWeapon() then

		if CurEnt:IsVehicle() then
			Item.vehiclescript = table.LowerKeyNames(CurEnt:GetKeyValues()).vehiclescript
		end

		Item.SID = ply.SID


		if (EntClass=="spawned_shipment") then
			for k,v in pairs(CustomShipments) do
				if string.lower(CustomShipments[CurEnt:Getcontents()].name) == string.lower(v.name) then
					Item.key = k
					Item.amount = CurEnt:Getcount()
				end
			end
		end

		if !CurEnt:OwnedBy(ply) then
			Item.wasowned = 1
		else
			Item.wasowned = 0
		end

		


		if EntClass=="gunlab" then
			Item.labprice = CurEnt:Getprice()
		end
	
		if EntClass=="normal_money_printer" or EntClass=="ruby_money_printer" or EntClass=="gold_money_printer" or EntClass=="nuclear_money_printer" then
			//CurEnt:stopPrint()
			Item.storedmoney = CurEnt:GetNWInt("PrintA")
		end

		if EntClass=="spawned_weapon" then
			Item.weaponclass = CurEnt.weaponclass
			if CurEnt.clip1 then
				Item.clip1 = CurEnt.clip1
				Item.clip2 = CurEnt.clip2
			else
				Item.clip1 = weapons.Get(CurEnt.weaponclass).Primary.ClipSize+weapons.Get(CurEnt.weaponclass).Primary.DefaultClip
				Item.clip2 = weapons.Get(CurEnt.weaponclass).Secondary.ClipSize+weapons.Get(CurEnt.weaponclass).Secondary.DefaultClip
			end
		end

		if CurEnt:IsWeapon() then
			Item.class = "spawned_weapon"
			EntClass = "spawned_weapon"
			Item.weaponclass = CurEnt:GetClass()
			Item.clip1 = CurEnt:Clip1()
			Item.clip2 = CurEnt:Clip2()
		end


		table.insert(ply:GetTable().Inventory, {ID = ID, class = EntClass, model = Item.model, amount = Item.amount, wepkey = Item.key, wasowned = Item.wasowned, labprice = Item.labprice, storedmoney = Item.storedmoney, weaponclass = Item.weaponclass, vehiclescript = Item.vehiclescript, clip1 = Item.clip1, clip2 = Item.clip2 } )
		saveInventory(ply)

	
	else
		GAMEMODE:Notify(ply, 1, 4, "You can not put ".. "that" .." in your Inventory!")
		return
	end

	CurEnt:Remove()
end
	
concommand.Add("inventorywep", function(ply) inventoryItem(ply:GetActiveWeapon(),ply) end)


function SWEP:SecondaryAttack()
	self.Weapon:SetNextSecondaryFire(CurTime() + 0.2)

	if CLIENT then return end

	local Steam = self.Owner:SteamID()


	if not self.Owner:GetTable().Inventory or #self.Owner:GetTable().Inventory <= 0 then
		GAMEMODE:Notify(self.Owner, 1, 4, "Your Inventory contains no items.")
		return
	end

	self:NewSetWeaponHoldType("pistol")
	timer.Simple(0.2, function() if self:IsValid() then self:NewSetWeaponHoldType("normal") end end)

	spawnFromInventory(self.Owner, #self.Owner:GetTable().Inventory)
end



SWEP.OnceReload = false
function SWEP:Reload()



	if self.Weapon.OnceReload or CLIENT then return end
	if SERVER then
		self.Weapon.OnceReload = true
		timer.Simple(1, function() self.Weapon.OnceReload = false end)
	end


	sendInventoryToClient(self.Owner)


end

if CLIENT then 


	//iconModels={}
	function openInventory( client )

		local ClientInventory = net.ReadTable()

	    //iconModel = iconModel or "models/MaxOfS2D/logo_gmod_b.mdl"

	    if Inventorymenu and Inventorymenu:IsValid() then 
	    	Inventorymenu:Close()
	    	return 
	    end


     	Inventorymenu = vgui.Create("DFrame")

     	local addit=0
     	if #ClientInventory%3 != 0 then
     		addit=1
     	end

    	Inventorymenu:SetSize(242,   20 + 25+   72*(((#ClientInventory-#ClientInventory%3)/3)+addit)    )
    	Inventorymenu:SetPos(ScrW()-Inventorymenu:GetWide()-65,ScrH()-Inventorymenu:GetTall() - 13)
    	Inventorymenu:SetTitle("Inventory  ( Reload with SWEP )")
    	Inventorymenu:SetDraggable(false)

    	Inventorymenu:MakePopup()

    	local Inventorylist = vgui.Create( "DPanelList", Inventorymenu )
		Inventorylist:SetPos( 10,25 )
		Inventorylist:SetSize( Inventorymenu:GetWide()-30, Inventorymenu:GetTall() )
		Inventorylist:SetSpacing( 10 )
		Inventorylist:EnableHorizontal( true )
		Inventorylist:EnableVerticalScrollbar( true )

		
		for i=1, #ClientInventory do
			local itemIcon = vgui.Create( "SpawnIcon", Inventorylist )
			itemIcon:SetModel( ClientInventory[i].model )
			itemIcon:SetTooltip(GetTooltip(ClientInventory[i]))
		 	Inventorylist:AddItem( itemIcon )
			itemIcon.DoClick = function()

				net.Start("netinventorySpawn")
					net.WriteInt(table.KeyFromValue(table.ClearKeys(DPanelList.GetItems(Inventorylist)),itemIcon), 4)
				net.SendToServer()
				if #DPanelList.GetItems(Inventorylist)<2 then Inventorymenu:Close() return end
				DPanelList.RemoveItem(Inventorylist,itemIcon)
				itemIcon:Remove()
				
		end


		
	end

	
 

end 

	function GetTooltip(Item)

		local Tooltipstring = ""

		Tooltipstring = Tooltipstring .. "Class: " .. Item.class .. "\n"

		if Item.class == "spawned_shipment" then
			Tooltipstring = Tooltipstring .. "Shipment of: " .. CustomShipments[Item.wepkey].name .. "\n" .. "Number left:" .. Item.amount
		elseif Item.class == "gunlab" then
			Tooltipstring = Tooltipstring .. "Gun Price:" .. Item.labprice .. "\n"
		elseif Item.class=="spawned_weapon" then
			Tooltipstring = Tooltipstring .. "Weapon Class: " .. Item.weaponclass .. "\n"
			Tooltipstring = Tooltipstring .. "Ammo: " .. Item.clip1 .. "/" .. Item.clip2 .. "\n"
		elseif Item.class=="normal_money_printer" or Item.class=="ruby_money_printer" or Item.class=="gold_money_printer" or Item.class=="nuclear_money_printer" then
			Tooltipstring = Tooltipstring .. "Holding: " .. "$" .. Item.storedmoney .. "\n"
		end

		return Tooltipstring
	end

	function closeInventory()
		if Inventorymenu and Inventorymenu:IsValid() then Inventorymenu:Close() end
	end

	
	concommand.Add("-inventory", function () closeInventory() end )

	concommand.Add("+inventory", function (ply) 

		net.Start("openmyinv")
		net.SendToServer()

	end )

	net.Receive( "netinventory", function ( length, ply ) openInventory(ply) end )

	hook.Add("StartChat", "playerIsChatting", function() playerIsChatting=true end)
	hook.Add("FinishChat", "playerIsDoneChatting", function() playerIsChatting=false end)

end


if SERVER then

	function spawnFromInventory(ply, itemID)
		
		Item = ply:GetTable().Inventory[itemID]


		local trace = {}
		trace.start = ply:EyePos()
		trace.endpos = trace.start + ply:GetAimVector() * 85
		trace.filter = ply
		local tr = util.TraceLine(trace)

		
			
		// Classes Start Here
		//----
		//--------
		//----

		if Item.class == "spawned_shipment" then
			local ent = ents.Create(Item.class)
			ent.SID = ply.SID
			ent:Setowning_ent(ply)
			ent:SetContents(Item.wepkey, Item.amount)

			ent:SetPos(Vector(tr.HitPos.x, tr.HitPos.y, tr.HitPos.z))
			ent.nodupe = true
			ent:Spawn()
			ent:SetPlayer(ply)


			local phys = ent:GetPhysicsObject()
			phys:Wake()
			table.remove(ply:GetTable().Inventory, itemID)

		end

		local tempEnt = ents.Create(Item.class)
		if tempEnt:IsVehicle() then
			local ent = ents.Create(Item.class)
			if Item.wasowned==1 then
				ent:Own(ply)
			end
			ent:SetModel(Item.model)

			ent:SetPos(Vector(tr.HitPos.x, tr.HitPos.y, tr.HitPos.z))
			if ent:GetKeyValues().VehicleScript then
				ent:SetKeyValue("VehicleScript", Item.vehiclescript)
			else
				ent:SetKeyValue("vehiclescript", Item.vehiclescript)
			end
			ent:Spawn()
			ent:Activate()
			table.remove(ply:GetTable().Inventory, itemID)
		end
		tempEnt:Remove()

		

		if Item.class == "gunlab" then
			local ent = ents.Create(Item.class)
			ent:SetPos(Vector(tr.HitPos.x, tr.HitPos.y, tr.HitPos.z))
			ent.SID = ply.SID
			ent.onlyremover = true
			ent:Spawn()
			ent:SetModel("models/props_c17/TrapPropeller_Engine.mdl")
			ent:PhysicsInit(SOLID_VPHYSICS)
			ent:SetMoveType(MOVETYPE_VPHYSICS)
			ent:SetSolid(SOLID_VPHYSICS)
			ent:SetUseType(SIMPLE_USE)
			local phys = ent:GetPhysicsObject()

			ent:Setprice(Item.labprice)
			phys:Wake()
			table.remove(ply:GetTable().Inventory, itemID)
		end

		if table.HasValue(simpleEnts,Item.class) then
			local ent = ents.Create(Item.class)
			ent:SetPos(Vector(tr.HitPos.x, tr.HitPos.y, tr.HitPos.z))
			ent:Spawn()
			ent:PhysicsInit(SOLID_VPHYSICS)
			ent:SetMoveType(MOVETYPE_VPHYSICS)
			ent:SetSolid(SOLID_VPHYSICS)
			ent:SetUseType(SIMPLE_USE)
			local phys = ent:GetPhysicsObject()

			phys:Wake()
			table.remove(ply:GetTable().Inventory, itemID)
		end


		if Item.class=="spawned_weapon" then
			local ent = ents.Create(Item.class)
			ent:SetModel(Item.model)
			ent.weaponclass = Item.weaponclass
			//ent.ammoadd = weapons.Get(Item.weaponclass) and weapons.Get(Item.weaponclass).Primary.DefaultClip
			ent:SetPos(Vector(tr.HitPos.x, tr.HitPos.y, tr.HitPos.z))
			ent.ShareGravgun = true
			ent.nodupe = true
			ent.clip1 = Item.clip1
			ent.clip2 = Item.clip2
			ent:Spawn()
			table.remove(ply:GetTable().Inventory, itemID)
		end


		if Item.class=="normal_money_printer" or Item.class=="ruby_money_printer" or Item.class=="gold_money_printer" or Item.class=="nuclear_money_printer" then
			ply["max"..Item.class] = ply["max"..Item.class] or 0

			if Item.class == "nuclear_money_printer" then 
				if ply["max"..Item.class] > 6 then
					GAMEMODE:Notify(ply, 1, 4, "6 at a time, bro...")
					return 
				end
			end

			if Item.class=="normal_money_printer" or Item.class=="ruby_money_printer" or Item.class=="gold_money_printer" then
				if ply["max"..Item.class] > 4 then
					GAMEMODE:Notify(ply, 1, 4, "4 at a time, bro...")
					return 
				end
			end

			local ent = ents.Create(Item.class)
			ent:SetModel(Item.model)
			ent:SetPos(Vector(tr.HitPos.x, tr.HitPos.y, tr.HitPos.z))
			ent.ShareGravgun = true
			ent.nodupe = true
			ply["max"..Item.class] = ply["max"..Item.class] + 1
			ent.dt.owning_ent = ply
			ent:Spawn()
			ent:SetNWInt("PrintA",Item.storedmoney)
			ent.dt.owning_ent = ply

			table.remove(ply:GetTable().Inventory, itemID)
		end
		
		saveInventory(ply)
	end



	function sendInventoryToClient(ply)

		if not ply:GetTable().Inventory or #ply:GetTable().Inventory < 1 then
			net.Start( "netinventory" )
				net.WriteTable({})
			net.Send( ply )
			return
		end


		net.Start( "netinventory" )
			net.WriteTable( ply:GetTable().Inventory )
		net.Send( ply )
	end



	net.Receive( "netinventorySpawn", function( length, client )
			spawnFromInventory(client, net.ReadInt(4))
	end )

	net.Receive( "openmyinv", function( length, client )
	     	sendInventoryToClient(client)
	end )

end